//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

#ifndef _IP_RESOLVER_YG_H__
#define _IP_RESOLVER_YG_H__

#include <wx/wx.h>
#include <wx/string.h>
#include <wx/thread.h>


#include <map>
#include <list>


struct CIPResolverObserver
{
	virtual void OnResolve(unsigned long lIP, const wxString& strDNSName, void* pCookie)=0;
};


class CIPResolver: protected wxThread
{
public:
								CIPResolver(void);
	virtual						~CIPResolver(void);

	void						Start();
	void						CleanJobList();
	void						Stop();

	void						SetObserver(CIPResolverObserver* pObserver) { m_pObserver = pObserver; } 
	bool						Resolve(unsigned long lIP, void* pCookie, wxString& strHostName);

protected:
	virtual void*				Entry();

	typedef struct tagJOBENTRY
	{
		bool operator==(const tagJOBENTRY& entry)
		{
			return lIp==entry.lIp;
		}
		
		time_t				tLast;
		unsigned long		lIp;
		typedef std::list<void*>	COOKIESLIST;
		COOKIESLIST			m_lstCookies;
	}JOBENTRY;

	void					ResolveEng(JOBENTRY& entry);
	template<typename T> bool ShrinkDB(T& db, time_t t, size_t stMAX );

private:

	bool						GetJob(JOBENTRY& entry);

//Anywhere we have only one client 
private:
	CIPResolverObserver*		m_pObserver;

	typedef struct tagRESENTRY
	{
		time_t		tLast;
		wxString	strDNSName;
	}RESENTRY;

	typedef std::map<unsigned long, JOBENTRY>	JOBLIST;
	JOBLIST						m_jobs;

	typedef std::map<unsigned long, RESENTRY> RESENTRIES;
	RESENTRIES					m_resolvedb;

	volatile bool				m_bThreadRun;
	volatile bool				m_bWorking;

	wxCriticalSection			m_csJobsGuard;
	wxCriticalSection			m_csEntriesGuard;
};

#endif //_IP_RESOLVER_YG_H__